package com.serkol.driving.learning.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.hutool.core.io.FileUtil;
import cn.hutool.crypto.digest.MD5;
import com.serkol.annotation.IsLogin;
import com.serkol.bean.MyPage;
import com.serkol.bean.Result;
import com.serkol.bean.UsersInfo;
import com.serkol.bean.WxMiniPhoneConfig;
import com.serkol.constant.AuthConstant;
import com.serkol.constant.ResultCode;
import com.serkol.constant.ResultConstant;
import com.serkol.driving.learning.entity.LoginLog;
import com.serkol.driving.learning.entity.Users;
import com.serkol.driving.learning.service.UsersService;
import com.serkol.exception.AuthException;
import com.serkol.exception.SerkolProjectException;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.File;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("api/users")
public class UsersApiController {


    @Autowired
    private UsersService userService;


    @Autowired
    private WxMaService wxMaService;


    @IsLogin
    @PostMapping("/wxMiniPhone")
    @ResponseBody
    public Result wxMiniPhone(@RequestBody @Valid WxMiniPhoneConfig wxMiniConfig) throws SerkolProjectException, WxErrorException, AuthException {
//wxMiniPhone
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(wxMiniConfig.getSessionKey(), wxMiniConfig.getEncryptedData(), wxMiniConfig.getIv());
        String phoneNumber = phoneNoInfo.getPhoneNumber();
        System.out.println(phoneNoInfo.getPhoneNumber());
        boolean flag = userService.editPhoneNumber(phoneNumber);
        //    System.out.println(phoneNoInfo.getPurePhoneNumber());
        if (flag) {
            return Result.ok(phoneNumber);
        } else {
            throw new AuthException(ResultCode.REQUEST_ERROR_NOT_ACCEPTABLE);
        }

    }

    //

    @IsLogin
    @GetMapping(value = "inviteCode", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] invitation(@RequestParam(value = "inviteUserId", defaultValue = "0") Long inviteUserId) throws WxErrorException {
        //String.valueOf(inviteUserId)
        File file = wxMaService.getQrcodeService().createQrcode("pages/index/user", 300);

        return FileUtil.readBytes(file);

    }

    //getAgentUserFeild

    //getAgentUserFeild

    @IsLogin
    @GetMapping("/currentUser")
    // @Cacheable(value = "HHHHHH", key = "'UsersApiController:findByList'")
    public Result currentUser() {

        LoginLog loginLog = AuthConstant.getLoginLog();
        System.out.println(loginLog);
        System.out.println(loginLog);

        Map<String, Object> one = userService.getCurrentUser();

        if (one != null) {
            return Result.ok(one);
        } else {
            return Result.failure(ResultConstant.EMPTIY);
        }

    }

    @IsLogin
    @GetMapping("/findById")
    public Result findById(@RequestParam(name = "userId", defaultValue = "1") long userId) {

        Map<String, Object> one = userService.findById(userId);

        if (one != null) {
            return Result.ok(one);
        } else {
            return Result.failure(ResultConstant.EMPTIY);
        }

    }

    @GetMapping("/findByOnId")
    public Result findByOnId(@RequestParam(name = "userId", defaultValue = "0") long userId) {

        Map<String, Object> one = userService.findById(userId);

        if (one != null) {
            return Result.ok(one);
        } else {
            return Result.failure(ResultConstant.EMPTIY);
        }

    }

    @IsLogin
    @GetMapping("/findByPageList")
    public Result findByPageList(@RequestParam(name = "pageSize", defaultValue = "10") int pageSize, @RequestParam(name = "page", defaultValue = "0") int page,
                                 @RequestParam(name = "invite", defaultValue = "") String invite
            , @RequestParam(name = "userName", defaultValue = "") String userName
            , @RequestParam(name = "nickname", defaultValue = "") String nickname
            , @RequestParam(name = "phone", defaultValue = "") String phone) {
        Result result = new Result();
        MyPage list = userService.findByList(pageSize, page, invite.trim(), userName.trim(), nickname.trim(), phone.trim());
        if (list.getSize() > 0) {
            result.setStatus(ResultConstant.SUCSESS);
            result.setData(list);
        } else {
            result.setStatus(ResultConstant.EMPTIY);
        }
        return result;
    }

    @IsLogin
    @GetMapping("/findByPageMiniList")
    public Result findByPageMiniList(@RequestParam(name = "pageSize", defaultValue = "10") int pageSize, @RequestParam(name = "page", defaultValue = "0") int page,
                                     @RequestParam(name = "invite", defaultValue = "") String invite
            , @RequestParam(name = "userName", defaultValue = "") String userName
            , @RequestParam(name = "nickname", defaultValue = "") String nickname
            , @RequestParam(name = "phone", defaultValue = "") String phone) {
        Result result = new Result();
        MyPage list = userService.findByList(pageSize, page, invite, userName, nickname, phone);

        result.setStatus(ResultConstant.SUCSESS);
        result.setData(list.getList());

        return result;
    }









    @IsLogin
    @PostMapping("edit")
    public Result edit(@RequestBody UsersInfo usersInfo) {
        System.out.println(usersInfo);
        if (userService.isPhoneAndIdValid(usersInfo.getPhone(), usersInfo.getId()) || !userService.isPhoneValid(usersInfo.getPhone())) {
            Users users = new Users();
            users.setId(usersInfo.getId());
            users.setPhone(usersInfo.getPhone());
            users.setUserName(usersInfo.getUserName());
            users.setInvite(usersInfo.getInvite());

            if (StringUtils.isNotEmpty(usersInfo.getPassword())) {
                MD5 md5 = MD5.create();
                String s = md5.digestHex(usersInfo.getPassword());
                users.setUserPassword(s);
            }

            if (StringUtils.isNotEmpty(usersInfo.getParentUser())) {
                if (userService.isPhoneValid(usersInfo.getParentUser())) {
                    Users byUserPhone = userService.findByUserPhone(usersInfo.getParentUser());
                    users.setParentUserId(byUserPhone.getId());

                } else {
                    return Result.failure();
                }
            }
            boolean b = userService.updateById(users);
            if (b) {

                    return Result.ok();

            } else {

                return Result.failure();
            }
        } else {
            return Result.failure();
        }

    }






    @IsLogin
    @GetMapping("serachByPhone")
    public Result serachByPhone(@RequestParam(value = "phone", defaultValue = "") String phone) {
        if (StringUtils.isNotEmpty(phone)) {
            Map<String, Object> byUserPhone = userService.findByUserAuthPhone(phone);
            if (byUserPhone != null) {
                return Result.ok(byUserPhone);
            } else {
                return Result.failure(ResultConstant.EMPTIY);
            }

        } else {
            return Result.failure();
        }

    }


    @IsLogin
    @GetMapping("/findMyParentList")
    public Result findMyParentList(@RequestParam(name = "userId", defaultValue = "0") long userId) {
        // System.out.println(pageSize+"------------|||||-----------"+current);



        List<Map<String, Object>> list = userService.findMyParentList(userId);
        //   List<Map<String, Object>> list = userService.listMaps(query);
        return Result.ok(list);
    }



}
